﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using PPI.Client.Logic.XML;
using PPI.Entities;
using PPI.Entities.Enumerator;
using PPI.Entities.Interface;
using PPI.Entities.XML;
using PPI.General;

namespace PPI.Client.Logic.Upload
{
    public class LUploadStrategyGPSImages : LUploadStrategyBase
    {
        public LUploadStrategyGPSImages(EXmlOutboxBase outbox) : base(outbox)
        {
        }

        public override void StartWork(BackgroundWorker worker, DoWorkEventArgs workerEvents)
        {
            StringBuilder _errorMessage = new StringBuilder();
            Int32 _TotalToUpload = 0;
            Int32 _CountUploaded = 0;

            if (m_OutboxDatabase.IsDataUploaded && !m_OutboxDatabase.IsImagesUploaded)
            {
                bool _FoundedProblems = false;
                List<EVendor_Visit_XMissionStructures_Image> _ImagesToUpload =
                    LVendor_Visit_XMissionStructures_Image.GetAll(m_OutboxDatabase.ConnectionString);

                _TotalToUpload += _ImagesToUpload.Count;
                _CountUploaded = _TotalToUpload;
                WebUploaderHelper _UploaderHelper = new WebUploaderHelper(Constants.K_WEBSITEUPLOADER);
                foreach (EVendor_Visit_XMissionStructures_Image i in _ImagesToUpload)
                {
                    if (worker.CancellationPending)
                    {
                        workerEvents.Cancel = true;
                        return;
                    }
                    if(i.ServerID == Int32.MinValue)
                    {
                        Int32 mobileId = i.Id;
                        i.Id = Int32.MinValue;

                        i.ServerID = LVendor_Visit_XMissionStructures_Image.Save(i);
                        i.Id = mobileId;
                        LVendor_Visit_XMissionStructures_Image.UpdateUploadedData(i, m_OutboxDatabase.ConnectionString);
                        i.Id = i.ServerID;
                        
                        string _FileName = i.Asset.ServerID + "_" + i.ServerID + ".jpg";
                        string _FolderName = DirHelper.GetImageDirectory(i.Asset.ServerID, i.ServerID);

                        if(i.ImageFile.Exists)
                            _UploaderHelper.Upload(_FolderName, _FileName, i.ImageFile, Enum.GetName(typeof(DatabaseTypes), m_OutboxDatabase.DatabaseType));
                    }
                    _CountUploaded--;
                    worker.ReportProgress(ReportProgress(_CountUploaded, _TotalToUpload));
                    System.Threading.Thread.Sleep(300);
                }
            }
        }

        public override void FinishWork()
        {
            LXmlOutbox _serviceLogic = new LXmlOutbox(m_OutboxDatabase);
            _serviceLogic.CopyToSentFolder();
          
        }
    }
}
